package pers.hll.visitor;

import com.github.javaparser.ast.ImportDeclaration;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.ConstructorDeclaration;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;

import java.util.ArrayList;
import java.util.List;

public class ConstantClassVisitor extends VoidVisitorAdapter<Void> {

    private final List<ImportDeclaration> importsToRemove = new ArrayList<>();

    @Override
    public void visit(FieldDeclaration fd, Void arg) {
        super.visit(fd, arg);
        fd.setModifiers(Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC, Modifier.Keyword.FINAL);
    }

    @Override
    public void visit(ClassOrInterfaceDeclaration cd, Void arg) {
        String constantClassName = "ConstantClass";
        boolean hasConstantClassAnnotation = cd.getAnnotations()
                .stream()
                .anyMatch(annotation -> annotation.getNameAsString().equals(constantClassName));
        if (hasConstantClassAnnotation) {
            cd.getAnnotations().removeIf(annotation -> annotation.getNameAsString().equals(constantClassName));
        }
        cd.addModifier(Modifier.Keyword.FINAL);
        super.visit(cd, arg);
    }

    @Override
    public void visit(ConstructorDeclaration cd, Void arg) {
        cd.setModifiers(Modifier.Keyword.PRIVATE);
        super.visit(cd, arg);
    }

    @Override
    public void visit(ImportDeclaration importDeclaration, Void arg) {
        if ("pers.hll.annotation.ConstantClass".equals(importDeclaration.getNameAsString())) {
            importsToRemove.add(importDeclaration);
        }
        super.visit(importDeclaration, arg);
    }

    public void removeImportsAfterVisit() {
        importsToRemove.forEach(ImportDeclaration::remove);
    }
}